import {defineStore} from 'pinia';
import {signIn, getSignRecord, generateVerificationCode} from '@/api/user/sign.js';
import {ElMessage} from 'element-plus';

export const useSignStore = defineStore('sign', {
    state: () => ({
        signRecords: [],
        loading: false,
        page: 1,
        pageSize: 10,
        total: 0,
        code: '', // 存储验证码
    }),
    actions: {
        // 签到
        async signIn(verificationCode) {
            try {
                const response = await signIn(verificationCode);
                if (response.code === 200) {
                    return true;
                } else {
                    console.error(response.message || '签到失败');
                    ElMessage.error({message: response.message || "签到失败", duration: 3000});
                    return false;
                }
            } catch (error) {
                console.error(error.message || '签到失败');
                ElMessage.error({message: error.message || "签到失败", duration: 3000});
                return false;
            }
        },
        // 生成验证码
        async generateVerificationCode() {
            this.loading = true;
            try {
                const response = await generateVerificationCode();
                if (response.code === 200) {
                    return response.data.code;
                } else {
                    console.error(response.message || '获取验证码失败');
                    ElMessage.error({message: response.message || "获取验证码失败", duration: 3000});
                    return false;
                }
            } catch (error) {
                console.error(error.message || '获取验证码失败');
                ElMessage.error({message: error.message || "获取验证码失败", duration: 3000});
                return false;
            } finally {
                this.loading = false;
            }
        },
        // 获取签到记录
        async getSignRecords(data) {
            this.loading = true;
            try {
                const response = await getSignRecord(data);
                if (response.code === 200) {
                    this.signRecords = response.data.items;
                    this.total = response.data.total;
                } else {
                    console.error(response.message || '获取签到记录失败');
                    ElMessage.error({message: response.message || "获取签到记录失败", duration: 3000});
                }
            } catch (error) {
                console.error(error.message || '获取签到记录失败');
                ElMessage.error({message: error.message || "获取签到记录失败", duration: 3000});
            } finally {
                this.loading = false;
            }
        },
        // 设置当前页码
        setPage(page) {
            this.page = page;
        },
        // 设置每页显示记录数
        setPageSize(pageSize) {
            this.pageSize = pageSize;
        },
    },
});